/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.knolle.vista;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import modelo.Lotes;
import modelo.UnidadMedidaSuperficie;
import org.knolle.modelo.LotesController;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.UndoRedo;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;


/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.knolle.vista//EditarParcela//EN",
autostore = false)
@TopComponent.Description(preferredID = "EditarParcelaTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = true)
@ActionID(category = "Window", id = "org.knolle.vista.EditarParcelaTopComponent")
@ActionReference(path = "Menu/Window" /*
 * , position = 333
 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_EditarParcelaAction",
preferredID = "EditarParcelaTopComponent")
@Messages({
    "CTL_EditarParcelaAction=EditarParcela",
    "CTL_EditarParcelaTopComponent=EditarParcela Window",
    "HINT_EditarParcelaTopComponent=This is a EditarParcela window"
})
public final class EditarLoteTopComponent extends TopComponent implements LookupListener{
    
    //El objeto actual
    private Lotes actual;
    //El lookupResult para pasar objetos entre ventanas
    private Lookup.Result result = null;
    //El manejador para hacer y deshacer
    //Aca hay que filtrar que ctr+z sea deshacer ctr+y sea rehacer
    //que algunas teclas no tengan efecto y otras cositas
    private UndoRedo.Manager manager = new UndoRedo.Manager();
    //Este es el Nombre de la ventana de vista de los Lotes sirve para buscar el lote
    private static final String VENTANA_VISTA_ID = "ParcelasVistaTopComponent"; 

    public EditarLoteTopComponent() {
        initComponents();
        setName(Bundle.CTL_EditarParcelaTopComponent());
        setToolTipText(Bundle.HINT_EditarParcelaTopComponent());
        putClientProperty(TopComponent.PROP_KEEP_PREFERRED_SIZE_WHEN_SLIDED_IN, Boolean.TRUE);
        //Acciones de deshacer
        jLoteNombre.getDocument().addUndoableEditListener(manager);
        jLoteSuperfice.getDocument().addUndoableEditListener(manager);
        txtAreaLoteUbicacion.getDocument().addUndoableEditListener(manager); 
        //valoresIniciales();
        initComponentes(); 
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jPanel1 = new javax.swing.JPanel();
        jLoteNombre = new javax.swing.JTextField();
        jLoteSuperfice = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cmbUnidadMedida = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtAreaLoteUbicacion = new javax.swing.JTextArea();

        jLoteNombre.setText(org.openide.util.NbBundle.getMessage(EditarLoteTopComponent.class, "EditarLoteTopComponent.jLoteNombre.text")); // NOI18N
        jLoteNombre.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jLoteNombreFocusGained(evt);
            }
        });

        jLoteSuperfice.setText(org.openide.util.NbBundle.getMessage(EditarLoteTopComponent.class, "EditarLoteTopComponent.jLoteSuperfice.text")); // NOI18N
        jLoteSuperfice.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jLoteSuperficeFocusGained(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(EditarLoteTopComponent.class, "EditarLoteTopComponent.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(EditarLoteTopComponent.class, "EditarLoteTopComponent.jLabel2.text")); // NOI18N

        cmbUnidadMedida.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        /**
        * Generado por marcelo
        */
        cmbUnidadMedida.removeAllItems();
        List<UnidadMedidaSuperficie> unidadList = LotesController.getUnidades();
        for (UnidadMedidaSuperficie u: unidadList ){
            cmbUnidadMedida.addItem(u);
        }
        cmbUnidadMedida.setSelectedIndex(LotesController.InicioComboSupuerficie);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(EditarLoteTopComponent.class, "EditarLoteTopComponent.jLabel3.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(EditarLoteTopComponent.class, "EditarLoteTopComponent.jLabel4.text")); // NOI18N

        txtAreaLoteUbicacion.setColumns(20);
        txtAreaLoteUbicacion.setRows(5);
        txtAreaLoteUbicacion.setText(org.openide.util.NbBundle.getMessage(EditarLoteTopComponent.class, "EditarLoteTopComponent.txtAreaLoteUbicacion.text")); // NOI18N
        txtAreaLoteUbicacion.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtAreaLoteUbicacionFocusGained(evt);
            }
        });
        jScrollPane1.setViewportView(txtAreaLoteUbicacion);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addGap(52, 52, 52)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cmbUnidadMedida, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jLoteSuperfice, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLoteNombre, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)))
                .addContainerGap(27, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLoteNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLoteSuperfice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbUnidadMedida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 50, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jLoteNombreFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jLoteNombreFocusGained
        // TODO add your handling code here:
        //Cuando en el control ingresa el usuario.
        jLoteNombre.selectAll();
    }//GEN-LAST:event_jLoteNombreFocusGained

    private void jLoteSuperficeFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jLoteSuperficeFocusGained
        // TODO add your handling code here:
        jLoteSuperfice.selectAll();
        
    }//GEN-LAST:event_jLoteSuperficeFocusGained
    
    private void txtAreaLoteUbicacionFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtAreaLoteUbicacionFocusGained
        // TODO add your handling code here:
        txtAreaLoteUbicacion.selectAll();
    }//GEN-LAST:event_txtAreaLoteUbicacionFocusGained

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cmbUnidadMedida;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jLoteNombre;
    private javax.swing.JTextField jLoteSuperfice;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtAreaLoteUbicacion;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
        // Capturar Los eventos del lookup
        result = WindowManager.getDefault().findTopComponent(VENTANA_VISTA_ID).getLookup().lookupResult(Lotes.class);
        result.addLookupListener(this);
        resultChanged(new LookupEvent(result));
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
        // Remover el listener de eventos
        result.removeLookupListener(this);
        result = null;
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
    
    private void initComponentes(){
       /**
        * Consultar datos en la base de datos y cargarlos en el combo
        */ 
       
       this.actual = new Lotes();
        //Leer todas las propiedades importantes y guardarlas
//        cmbUnidadMedida.removeAllItems();
//        List<UnidadMedidaSuperficie> unidadList = LotesController.getUnidades();
//        for (UnidadMedidaSuperficie u: unidadList ){
//            cmbUnidadMedida.addItem(u);
//        }
//        cmbUnidadMedida.setSelectedIndex(LotesController.InicioComboSupuerficie);
//        //Grabe los datos en la base de datos entonces debo inicializar los controles
        if (bAgregarMas) {
            jLoteNombre.setText(jLoteNombreOld);
            jLoteSuperfice.setText(jLoteSuperficieOld);
            txtAreaLoteUbicacion.setText(jLoteUbicacionOld);
        }
    }
    
    //Posiblemente va a volar todo este codigo
    private String jLoteNombreOld;
    private String jLoteSuperficieOld;
    private String jLoteUbicacionOld;
    private Boolean bAgregarMas = false;
    private void valoresIniciales(){
        jLoteNombreOld = jLoteNombre.getText();
        jLoteSuperficieOld = jLoteSuperfice.getText();
        jLoteUbicacionOld = txtAreaLoteUbicacion.getText();
        
    }
    //fin de lo que se borrara

    /**
     * Metodo para capturar en cual celda se realizo el click, para no hacer el
     * doble click
     * @param lookupEvent 
     */
    
    @Override
    public void resultChanged(LookupEvent lookupEvent) {
        //throw new UnsupportedOperationException("Not supported yet.");
        Lookup.Result r = (Lookup.Result) lookupEvent.getSource();
        Collection<modelo.Lotes> lotes = r.allInstances();
        if (!lotes.isEmpty()) {
            for (Lotes lote : lotes) {
                jLoteNombre.setText(lote.getNombre());
                jLoteSuperfice.setText(lote.getSuperficie().toString());
                //Setear el combo al valor correcto
                   //No son iguales setear el combo
               cmbUnidadMedida.setSelectedIndex(lote.getUnidadMedidaSuperficie().getId() - 1); 
                txtAreaLoteUbicacion.setText(lote.getUbicacion());
            }
        } else {
                jLoteNombre.setText("[Ingrese el nombre]");
                jLoteSuperfice.setText("[Ingrese la superficie]");
                cmbUnidadMedida.setSelectedIndex(LotesController.InicioComboSupuerficie);
                txtAreaLoteUbicacion.setText("[Ingrese la ubicacion]");
            
        }
        
    }

    @Override
    public UndoRedo getUndoRedo() {
        //Metodo para Deshacer y rehacer
        return manager;
    }
}
